﻿using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using System.Text.RegularExpressions;

namespace EasyXaf.EntityDesigner.Commands;

public class CreateEntityCommand : ICommand
{
    public bool CanExecute(string command)
    {
        if (!string.IsNullOrWhiteSpace(command))
        {
            return command.StartsWith('+');
        }
        return false;
    }

    public void Execute(string command, CommandContext context)
    {
        var matches = Regex.Matches(command[1..].Trim(), @"(?<=\s|^).*?(?=\s|$)").Cast<Match>();

        var entityName = matches.FirstOrDefault()?.Value;
        if (string.IsNullOrWhiteSpace(entityName))
        {
            throw new CommandException(command, "实体名称不能为空");
        }

        var entity = context.DomainModel.VisualEntities.FirstOrDefault(e => e.Name == entityName);
        if (entity != null)
        {
            throw new CommandException(command, $"实体 '{entityName}' 已存在");
        }

        entity = context.ObjectSpace.CreateObject<Entity>();
        entity.Name = entityName;
        entity.Caption = matches.Skip(1).FirstOrDefault()?.Value;
        entity.DomainModel = context.DomainModel;
        entity.SetLocation(context.ViewportBounds, context.DomainModel);

        context.CurrentEntity = entity;
    }
}
